package com.yogee.topseller.activity.my;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.login.view.impl.GuideLoginRegist;
import com.yogee.topseller.adapter.OrderImgAdapter;
import com.yogee.topseller.adapter.PhotoPageAdapter;
import com.yogee.topseller.bean.OrderInfoBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.OrderDMLayout;
import com.yogee.topseller.layout.OrderLILayout;
import com.yogee.topseller.layout.PaymentExplainFragment;
import com.yogee.topseller.layout.TitleLayout;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.view.BasicDialog;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailsActivity extends HttpActivity implements OrderImgAdapter.OnItemPhotoClickListener, PhotoPageAdapter.OnPageItemClickListener, OrderDMLayout.UpdateUiListener {

    @BindView(R.id.order_details_layout)
    TitleLayout titleLayout;
    @BindView(R.id.order_details_yy_iv)
    ImageView orderDetailsYyIv;
    @BindView(R.id.order_details_yy_tv)
    TextView orderDetailsYyTv;
    @BindView(R.id.order_details_pz_iv)
    ImageView orderDetailsPzIv;
    @BindView(R.id.order_details_pz_tv)
    TextView orderDetailsPzTv;
    @BindView(R.id.order_details_ht_iv)
    ImageView orderDetailsHtIv;
    @BindView(R.id.order_details_ht_tv)
    TextView orderDetailsHtTv;
    @BindView(R.id.order_details_yj_iv)
    ImageView orderDetailsYjIv;
    @BindView(R.id.order_details_yj_tv)
    TextView orderDetailsYjTv;
    @BindView(R.id.order_details_iv)
    ImageView orderDetailsIv;
    @BindView(R.id.order_gone_details_ll)
    LinearLayout orderGoneDetailsLl;
    @BindView(R.id.order_news_name_tv)
    TextView orderNewsNameTv;
    @BindView(R.id.order_news_mj_tv)
    TextView orderNewsMjTv;
    @BindView(R.id.order_news_details_tv)
    TextView orderNewsDetailsTv;
    @BindView(R.id.order_news_details_rl)
    LinearLayout orderNewsDetailsRl;
    @BindView(R.id.order_news_qt_money_tv)
    TextView orderNewsQtMoneyTv;
    @BindView(R.id.order_news_sy_tv)
    TextView orderNewsSyTv;
    @BindView(R.id.order_news_month_tv)
    TextView orderNewsMonthTv;
    @BindView(R.id.my_order_call_iv)
    ImageButton myOrderCallIv;
    @BindView(R.id.my_order_li_layout)
    OrderLILayout myOrderLiLayout;
    @BindView(R.id.my_order_dm_layout)
    OrderDMLayout myOrderDmLayout;
    @BindView(R.id.order_gone_details_rv)
    RecyclerView imgRv;
    @BindView(R.id.my_order_vp)
    ViewPager myOrderVp;
    @BindView(R.id.order_details_money_title_tv)
    TextView moneyTitleTv;
    @BindView(R.id.order_details_money_tv)
    TextView moneyTv;
    @BindView(R.id.order_details_time_title_tv)
    TextView timeTitleTv;
    @BindView(R.id.order_details_time_tv)
    TextView timeTv;
    @BindView(R.id.order_details_premoney_title_tv)
    TextView premoneyTitleTv;
    @BindView(R.id.order_details_premoney_tv)
    TextView premoneyTv;
    @BindView(R.id.order_details_owner_tv)
    TextView ownerTv;
    @BindView(R.id.order_details_tel_tv)
    TextView telTv;
    @BindView(R.id.order_details_mj_time_ll)
    LinearLayout miTimeLl;
    @BindView(R.id.order_payment_explain_tv)
    TextView explainTv;
    @BindView(R.id.order_instruct_ll)
    LinearLayout instructLl;
    @BindView(R.id.order_instruct_tv)
    TextView instructTv;
    @BindView(R.id.order_details_timeout_tv)
    TextView timeoutTv;
    @BindView(R.id.tv_yy_bottom)
    TextView tv_yy_bottom;
    @BindView(R.id.tv_dk_bottom)
    TextView tv_dk_bottom;
    @BindView(R.id.tv_ht_bottom)
    TextView tv_ht_bottom;
    @BindView(R.id.tv_yj_bottom)
    TextView tv_yj_bottom;
    @BindView(R.id.img_yu)
    ImageView img_yu;
    @BindView(R.id.img_tu)
    ImageView img_tu;
    @BindView(R.id.order_news_yj_tv)
    TextView order_news_yj_tv;
    @BindView(R.id.order_news_pro_tv)
    TextView order_news_pro_tv;
    @BindView(R.id.order_news_mj_pb)
    ProgressBar order_news_mj_pb;


    private OrderImgAdapter imgAdapter;//图片的适配器

    private boolean isOrderMV = false;
    private int type;
    private PhotoPageAdapter photoPageAdapter;
    private String proId;
    private String telephone;
    private List<String> img;//上传凭证等图片集合

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            proId = getIntent().getStringExtra("proId");
        }
        titleLayout.setTitle("我的订单");
        titleLayout.setActivity(this);
        imgRv.setHasFixedSize(true);
        imgRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        imgAdapter = new OrderImgAdapter(this);
        imgRv.setAdapter(imgAdapter);
        imgAdapter.setOnItemPhotoClickListener(this);
        photoPageAdapter = new PhotoPageAdapter(this);
        photoPageAdapter.setOnPageItemClickListener(this);
        myOrderDmLayout.setListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        orderInfo(AppUtil.getUserId(this), proId);
    }

    @OnClick({R.id.order_details_rl, R.id.order_payment_explain_tv, R.id.my_order_call_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.order_details_rl:
                if (isOrderMV) {//如果是打开状态
                    isOrderMV = false;
                    orderDetailsIv.setImageResource(R.mipmap.product_pulldown_black);
                    orderGoneDetailsLl.setVisibility(View.GONE);
                } else {//如果是关闭状态
                    isOrderMV = true;
                    orderDetailsIv.setImageResource(R.mipmap.product_packup_black);
                    orderGoneDetailsLl.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.order_payment_explain_tv://逾期赔付说明
                new PaymentExplainFragment().show(getFragmentManager(), "dialog");
                break;
            case R.id.my_order_call_iv://咨询电话
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + telephone);
                intent.setData(data);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onItemPhotoClick(int pos) {
        myOrderVp.setVisibility(View.VISIBLE);
        photoPageAdapter.addData(img);
        myOrderVp.setAdapter(photoPageAdapter);
        myOrderVp.setCurrentItem(pos);
    }

    @Override
    public void onPageItemClick() {
        myOrderVp.setVisibility(View.GONE);
    }

    private void orderInfo(String userid, String orderId) {
        HttpManager.getInstance().orderInfo(userid, orderId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<OrderInfoBean>() {
            @Override
            public void onNext(OrderInfoBean o) {
                setViewData(o);
            }
        }, this));
    }

    private void toastMessage(String isAddress) {
        BasicDialog.Builder builder = new BasicDialog.Builder(this);
        if (isAddress.equals("0")) {
            builder.setMessage("请填写一个收货地址")
                    .setPositiveButton("确定", new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(OrderDetailsActivity.this, ContractAddressManageActivity.class);
                            OrderDetailsActivity.this.startActivity(intent);
                            dialog.dismiss();
                        }

                    })
                    .setNegativeButton("忽略", new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
        } else {
            builder.setMessage("添加银行卡")
                    .setPositiveButton("确定", new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(OrderDetailsActivity.this, AccountManagerActivity.class);
                            OrderDetailsActivity.this.startActivity(intent);
                            dialog.dismiss();
                        }

                    })
                    .setNegativeButton("忽略", new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
        }
        builder.create().show();
    }

    private void setViewData(OrderInfoBean o) {
        telephone = o.getTelephone();
        //配送信息
        //订单状态
        switch (o.getOrderStats()) {
            case "1":
                moneyTitleTv.setText("预计金额：");
                timeTitleTv.setText("预约时间：");
                premoneyTitleTv.setText("预计获得佣金：");
//                orderDetailsYyIv.setImageResource(R.mipmap.order_subscribe_red);
                orderDetailsYyTv.setTextColor(getResources().getColor(R.color.colorStyle));
                tv_yy_bottom.setVisibility(View.VISIBLE);
                tv_dk_bottom.setVisibility(View.INVISIBLE);
                tv_ht_bottom.setVisibility(View.INVISIBLE);
                tv_yj_bottom.setVisibility(View.INVISIBLE);
                myOrderLiLayout.setVisibility(View.GONE);
                myOrderDmLayout.setVisibility(View.VISIBLE);
                myOrderDmLayout.setBean(proId, o);
                break;
            case "2":
                moneyTitleTv.setText("确认金额：");
                timeTitleTv.setText("确认时间：");
                premoneyTitleTv.setText("预计获得佣金：");
                tv_yy_bottom.setVisibility(View.INVISIBLE);
                tv_dk_bottom.setVisibility(View.VISIBLE);
                tv_ht_bottom.setVisibility(View.INVISIBLE);
                tv_yj_bottom.setVisibility(View.INVISIBLE);
//                orderDetailsPzIv.setImageResource(R.mipmap.order_money_red);
                orderDetailsPzTv.setTextColor(getResources().getColor(R.color.colorStyle));
                myOrderLiLayout.setVisibility(View.GONE);
                myOrderDmLayout.setVisibility(View.VISIBLE);
                myOrderDmLayout.setBean(proId, o);
                break;
            case "3":
                moneyTitleTv.setText("已购买：");
                timeTitleTv.setText("购买时间：");
                premoneyTitleTv.setText("获得佣金：");
                tv_yy_bottom.setVisibility(View.INVISIBLE);
                tv_dk_bottom.setVisibility(View.INVISIBLE);
                tv_ht_bottom.setVisibility(View.VISIBLE);
                tv_yj_bottom.setVisibility(View.INVISIBLE);
//                orderDetailsHtIv.setImageResource(R.mipmap.order_contract_red);
                orderDetailsHtTv.setTextColor(getResources().getColor(R.color.colorStyle));
                if (o.getIsReturnBack().equals("0")) {
                    myOrderDmLayout.setBean(proId, o);
                    myOrderDmLayout.setVisibility(View.VISIBLE);
                    myOrderLiLayout.setVisibility(View.GONE);
                } else {
                    myOrderLiLayout.addData(o, proId);
                    myOrderDmLayout.setVisibility(View.GONE);
                    myOrderLiLayout.setVisibility(View.VISIBLE);
                }
                break;
            case "4":
                moneyTitleTv.setText("已购买：");
                timeTitleTv.setText("购买时间：");
                premoneyTitleTv.setText("获得佣金：");
                tv_yy_bottom.setVisibility(View.INVISIBLE);
                tv_dk_bottom.setVisibility(View.INVISIBLE);
                tv_ht_bottom.setVisibility(View.INVISIBLE);
                tv_yj_bottom.setVisibility(View.VISIBLE);
//                orderDetailsYjIv.setImageResource(R.mipmap.order_commission_red);
                orderDetailsYjTv.setTextColor(getResources().getColor(R.color.colorStyle));
                myOrderLiLayout.setVisibility(View.VISIBLE);
                myOrderDmLayout.setVisibility(View.GONE);
                myOrderLiLayout.addData(o, proId);
                break;
            case "5":
                tv_yy_bottom.setVisibility(View.INVISIBLE);
                tv_dk_bottom.setVisibility(View.INVISIBLE);
                tv_ht_bottom.setVisibility(View.INVISIBLE);
                tv_yj_bottom.setVisibility(View.VISIBLE);
//                orderDetailsYjIv.setImageResource(R.mipmap.order_commission_red);
                orderDetailsYjTv.setTextColor(getResources().getColor(R.color.colorStyle));
                moneyTitleTv.setText("已购买：");
                timeTitleTv.setText("购买时间：");
                premoneyTitleTv.setText("获得佣金：");
                myOrderLiLayout.setVisibility(View.GONE);
                myOrderDmLayout.setVisibility(View.GONE);
                break;
        }
        if (o.getOrderInfoList().get(0).getTimeout() != null) {
            if (o.getIsSignReturn().equals("1") && o.getIsFast().equals("1") && o.getOrderStats().equals("3")) {
                explainTv.setVisibility(View.VISIBLE);
                miTimeLl.setVisibility(View.VISIBLE);
                String s = o.getOrderInfoList().get(0).getTimeout();
                if (s.equals("超时")) {
                    timeoutTv.setText(s);
                } else {
                    startTimeOut(Integer.valueOf(s));
                }
            }
        }

        //订单信息
        OrderInfoBean.OrderInfoListBean orderInfoBean = o.getOrderInfoList().get(0);
        moneyTv.setText(orderInfoBean.getMoney());
        timeTv.setText(orderInfoBean.getTime());
        premoneyTv.setText(orderInfoBean.getPreMoney());
        ownerTv.setText(orderInfoBean.getOwner());
        telTv.setText(orderInfoBean.getTel());
        if (orderInfoBean.getImg().equals("0")) {
            imgRv.setVisibility(View.GONE);
        } else {
            img = Arrays.asList(orderInfoBean.getImg().split(","));
            imgRv.setVisibility(View.VISIBLE);
            imgAdapter.addData(img);
        }
        if (orderInfoBean.getInstruct().equals("0")) {
            instructLl.setVisibility(View.GONE);
        }
        instructTv.setText(orderInfoBean.getInstruct());//提示信息
        //产品详情
        OrderInfoBean.ProductListBean proBean = o.getProductList().get(0);
        String labels = "";
        List<String> list = Arrays.asList(proBean.getLabels().split(","));


        orderNewsDetailsTv.setText(proBean.getProType());
        orderNewsNameTv.setText(proBean.getName());
        orderNewsQtMoneyTv.setText(proBean.getStartAmount());
        orderNewsSyTv.setText(proBean.getExpectReturn());
        orderNewsMonthTv.setText(proBean.getInvestmentTerm());
        // 预热和图片
        if(proBean.getImgstatus().equals("1")){
            img_tu.setVisibility(View.VISIBLE);
        }else{
            img_tu.setVisibility(View.GONE);
        }

        if(proBean.getStatus().equals("预热中"))
            img_yu.setVisibility(View.VISIBLE);
        else{
            img_yu.setVisibility(View.GONE);
        }



        if (o.getDistributionList().get(0).getPopup().equals("1")) {
            toastMessage("0");
        }
    }

    @Override
    public void onUpdateClick(boolean isConfirm) {
        if (isConfirm) {//如果是确认费用
            ToastUtils.showToast(this, "确认费用成功");
        } else {
            BasicDialog.Builder builder = new BasicDialog.Builder(this);
            builder.setMessage("申请合同成功");
            builder.create().show();
        }
        orderInfo(AppUtil.getUserId(this), proId);
    }

    private void startTimeOut(int s) {
        CountDownTimer timer = new CountDownTimer(s * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeoutTv.setText(getHMS(millisUntilFinished));
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    private String getHMS(long s) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");//初始化Formatter的转换格式。  
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));

        String hms = formatter.format(s);

        return hms;
    }
}